/**
 * 用来保证棋盘数据内容
 */
const ChessBoardData = {
    // 棋盘数据
    data: null,
    blackChessColor: 'black',
    whiteChessColor: 'white'
}

function ChessBoardData_getData() {
    return ChessBoardData.data;
}

/**
 * 二维数字数组，其中有三种颜色，0：无、1：黑子、2：白子
 * @param data
 */
function ChessBoardData_fillData(data) {
    let chessData = ChessBoardData_getData();
    for (let i = 0; i < chessData.length; i++) {
        for (let j = 0; j < chessData[i].length; j++) {
            chessData[i][j].color = data[i][j];
        }
    }
    ChessBoardData_setData(chessData);
}

function ChessBoardData_setData(data) {
    ChessBoardData.data = data;
}

function ChessBoardData_getChessDrawPosition(xIndex, yIndex) {
    return ChessBoardData_getData()[xIndex][yIndex];
}

function ChessBoardData_reset() {
    let data = ChessBoardData_getData();
    for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].length; j++) {
            data[i][j].color = 0;
        }
    }
}

function ChessBoardData_init(rows, cols) {
    let data = new Array(rows);
    for (let i = 0; i < rows; i++) {
        data[i] = new Array(cols);
        for (let j = 0; j < cols; j++) {
            data[i][j] = {
                drawX: (i + 1) * gridSize,
                drawY: (j + 1) * gridSize,
                color: 0
            };
        }
    }
    ChessBoardData_setData(data);
}

/**
 * 落子
 * @return {boolean} true表示落子成功，false表示落子失败
 */
function ChessBoardData_playChess(x, y, color = 1) {
    let xIndex = x;
    let yIndex = y
    let data = ChessBoardData_getData();
    if (x < 0 || y < 0 || x >= data.length || y >= data[0].length) {
        console.error('落子位置超出棋盘', x, y);
        return false;
    }
    if (data[xIndex][yIndex].color !== 0) {
        console.error('该位置已有棋子', x, y);
        return false;
    }
    data[xIndex][yIndex].color = color;
    ChessBoardData_setData(data);
    return true;
}